/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.schedule.core.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.system.HostInfo;
import com.alibaba.fastjson2.JSON;
import info.peigen.hotpot.common.core.enums.YesOrNo;
import info.peigen.hotpot.component.schedule.core.domain.ScheduleNode;
import info.peigen.hotpot.component.schedule.core.job.ScheduleExecute;
import info.peigen.hotpot.component.schedule.core.repository.service.ScheduleNodeRepository;
import info.peigen.hotpot.component.schedule.facade.job.ScheduleFacadeJob;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.List;

/**
 * <b>(ScheduleNodeExecutor)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2023/7/12
 */
@Slf4j
@Component
public class ScheduleNodeExecutor {
    @Inject
    private ScheduleNodeRepository scheduleNodeRepository;
    @Inject
    private ScheduleExecute        scheduleExecute;

    public void execute() {
        log.debug("定时任务执行，时间：{}", DateUtil.date());
        process();
        genScheduleNode();
    }

    private void process() {
        log.debug("定时任务执行");

        // 获取全部继承于ScheduleFacadeJob的任务
        List<ScheduleFacadeJob> beans = Solon.context().getBeansOfType(ScheduleFacadeJob.class);
        scheduleExecute.execute(beans);
    }

    private void genScheduleNode() {
        HostInfo     hostInfo = new HostInfo();
        ScheduleNode node     = scheduleNodeRepository.activeByIp(hostInfo.getAddress());
        log.debug(JSON.toJSONString(node));

        if (ObjectUtil.isNull(node)) {
            node = ScheduleNode.builder()
                    .nodeName(hostInfo.getName())
                    .ip(hostInfo.getAddress())
                    .port(Solon.cfg().getProperty("server.port"))
                    .cron(ScheduleNode.genCron())
                    .updateTime(DateUtil.date())
                    .yesOrNo(YesOrNo.Y)
                    .memo("首次创建")
                    .build();
        }
        scheduleNodeRepository.store(node);
    }
}
